package com.xindacloud.sms.adapter.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

/**
 * 消息类型工具类
 *
 * @author LvNing
 * @date 2019/9/27
 */
@Slf4j
public class MessageTypeHelp {

    public static boolean getMessageEnCoding(String encoding) {
        return Optional.ofNullable(encoding)
                .filter(StringUtils::isNotEmpty)
                .map(rs -> MessageTypeEnum.UNICODE.toString().equalsIgnoreCase(encoding))
                .orElse(false);
    }


    public static boolean isUnicode(String src) {
        if (StringUtils.isNotEmpty(src)) {
            int length = src.getBytes(StandardCharsets.UTF_8).length;
            if (length > src.length()) {
                return true;
            }
        }
        return false;
    }


    public static BigDecimal calcMessagePrice(BigDecimal price, Integer messageCount) {
        log.info("售价:{},短信条数:{}", price, messageCount);
        final BigDecimal multiply = price.multiply(BigDecimal.valueOf(Double.valueOf(messageCount)));
        log.info("需要支付的金额：{}", multiply);
        return multiply;
    }

    public static Integer calcMessageCount(String messageBody) {
        if (StringUtils.isEmpty(messageBody)) {
            return 0;
        }
        return isUnicode(messageBody) ? calcCountFor(messageBody, 70, 63) : calcCountFor(messageBody, 160, 153);
    }

    private static Integer calcCountFor(String str, int firstScalar, int secondScalar) {
        Integer initCount = 1;
        if (str.length() <= firstScalar) {
            return initCount;
        } else {
            String substring = str.substring(firstScalar);
            final int subStrLength = substring.length();
            int batchCount = subStrLength / secondScalar + (subStrLength % secondScalar == 0 ? 0 : 1);
            batchCount = initCount + batchCount;
            return batchCount;
        }
    }


    public enum MessageTypeEnum {
        /**
         * Message is a regular TEXT SMS message
         */
        TEXT,
        /**
         * Message is a binary SMS message with a custom UDH and binary payload
         */
        BINARY,
        /**
         * Message is a wap-push message to send a browsable / downloadable url to the handset
         */
        WAPPUSH,

        GSM,
        /**
         * Message is a unicode message, for sending messages in non-latin script to a supported handset
         */
        UNICODE;


        @Override
        public String toString() {
            return super.toString();
        }
    }
}
